# coding = utf-8

'''
分析gabor filter滤波之后的结果
'''

import cv2,os
import numpy as np
import matplotlib.pyplot as plt
import SimpleITK as sitk
from PIL import Image
import math

def garbor_filter4(image):
    image = image * 255
    image = image.astype(np.uint8)

    temp = np.zeros(image.shape)

    filters3 = []
    #theta2 = [0, 1 * np.pi / 6, 2 * np.pi / 6, 3 * np.pi / 6, 4 * np.pi / 6, 5 * np.pi / 6]
    theta2 = [0, 1 * np.pi / 6, 2 * np.pi / 6, 3 * np.pi / 6, 4 * np.pi / 6, 5 * np.pi/6]
    for item in theta2:
        kern = cv2.getGaborKernel((2, 2), sigma=1.0, theta=item, lambd=np.pi / 2.0, gamma=0.5, psi=0, ktype=cv2.CV_32F)
        kern /= 1.5 * kern.sum()
        filters3.append(kern)
    result3 = np.zeros_like(temp)
    for i in range(len(filters3)):
        accum = np.zeros_like(image)
        for kern in filters3[i]:
            fimg = cv2.filter2D(image, cv2.CV_8UC1, kern)
            accum = np.maximum(accum, fimg, accum)
        result3 += np.array(accum)
    result3 = result3 / len(filters3)
    result3 = result3.astype(np.uint8)
    result3 = cv2.equalizeHist(result3)

    return result3

def find_data(case_id, origion_id, index):
        big_image = "E:\Dataset\Liver\qiye\DongBeiDaXue2\image_venous\\data2_{}_venous.mha".format(origion_id)
        big_liver = "E:\Dataset\Liver\qiye\DongBeiDaXue2\liver\\data2_{}_liver_label.mha".format(origion_id)
        big_tumor = "E:\Dataset\Liver\qiye\DongBeiDaXue2\lesion\\data2_{}_lesion_label.mha".format(origion_id)
        big_fusion = "E:\predict\image_tumor\case_{}\\fusion\\{}.png".format(str(case_id).zfill(5), str(index).zfill(3))
        big_image = sitk.GetArrayFromImage(sitk.ReadImage(big_image))
        big_image[big_image <= -200] = -200
        big_image[big_image > 250] = 250
        big_image = (big_image + 200) / 450
        big_image = big_image[index]
        big_liver = sitk.GetArrayFromImage(sitk.ReadImage(big_liver))
        big_liver = big_liver[index]
        big_tumor = sitk.GetArrayFromImage(sitk.ReadImage(big_tumor))
        big_tumor = big_tumor[index]
        big_fusion = Image.open(big_fusion)
        return (big_image, big_fusion, big_liver, big_tumor)

def get_garbor_data(case_id, origion_id, index):
    (big_image, big_fusion, big_liver, big_tumor) = find_data(case_id=case_id, origion_id=origion_id, index=index)

    # garbor_filter4(big_image*big_liver)

    big_tumor[big_tumor > 0] = 1
    big_tumor = big_tumor * 255
    big_tumor = big_tumor.astype(np.uint8)
    contours, _ = cv2.findContours(big_tumor, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    big_image = big_image * big_liver
    # temp = garbor_filter4(big_image * big_liver)
    # temp = temp.astype(np.uint8)
    # temp = cv2.equalizeHist(temp)
    # temp = (255 - temp) * big_liver

    liver = (big_image) * big_liver
    liver = liver * 255
    liver = liver.astype(np.uint8)
    # liver = cv2.equalizeHist(liver)
    liver = cv2.cvtColor(liver, cv2.COLOR_GRAY2BGR)
    for counter in contours:
        data_list = []
        for t in range(counter.shape[0]):
            j = counter[t][0]
            data_list.append(j)
        cv2.polylines(liver, np.array([data_list], np.int32), True, [0, 255, 0], thickness=1)

    garbor_result = garbor_filter4(big_image)
    image = cv2.cvtColor(garbor_result, cv2.COLOR_GRAY2BGR)
    for counter in contours:
        data_list = []
        for t in range(counter.shape[0]):
            j = counter[t][0]
            data_list.append(j)
        cv2.polylines(image, np.array([data_list], np.int32), True, [0, 255, 0], thickness=1)

    data = cv2.medianBlur((255 - garbor_result) * big_liver, ksize=7)
    # data = cv2.blur((255 - garbor_result) * big_liver, ksize=(3,3))
    # data = (255 - garbor_result) * big_liver
    data[data <= 200] = 0
    data[data > 200] = 1

    liver_t = np.zeros(data.shape)
    temp = big_image * big_liver
    liver_t += (temp * data)
    liver_t += (temp * (1 - data) * 1.2)
    liver_t = liver_t / 1.2
    liver_t = liver_t * 255
    liver_t = liver_t.astype(np.uint8)
    liver_t = cv2.cvtColor(liver_t, cv2.COLOR_GRAY2BGR)
    for counter in contours:
        data_list = []
        for t in range(counter.shape[0]):
            j = counter[t][0]
            data_list.append(j)
        cv2.polylines(liver_t, np.array([data_list], np.int32), True, [0, 255, 0], thickness=1)

    return (liver,image, liver_t)


def main():
    (lable1, gabor1, fusion1) = get_garbor_data(case_id=67, origion_id="0415", index=134)
    (lable2, gabor2, fusion2) = get_garbor_data(case_id=67, origion_id="0415", index=135)
    (lable3, gabor3, fusion3) = get_garbor_data(case_id=67, origion_id="0415", index=136)

    plt.subplot(1, 3, 1)
    plt.imshow(lable1)
    plt.subplot(1, 3, 2)
    plt.imshow(lable2)
    plt.subplot(1, 3, 3)
    plt.imshow(lable3)
    plt.show()

    plt.subplot(1, 3, 1)
    plt.imshow(gabor1)
    plt.subplot(1, 3, 2)
    plt.imshow(gabor2)
    plt.subplot(1, 3, 3)
    plt.imshow(gabor3)
    plt.show()

    plt.subplot(1, 3, 1)
    plt.imshow(fusion1)
    plt.subplot(1, 3, 2)
    plt.imshow(fusion2)
    plt.subplot(1, 3, 3)
    plt.imshow(fusion3)
    plt.show()



if __name__ == '__main__':
    main()